package com.module.overview.ui.cardHistoryDetails.provider

import android.graphics.Typeface
import android.widget.TextView
import com.chad.library.adapter.base.provider.BaseItemProvider
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.common.app.data.bean.overView.HistoryDetailsModel
import com.common.base.app.extras.doOnIOThread
import com.common.base.app.extras.doOnUiThread
import com.common.base.utils.JsonUtils
import com.common.base.utils.SpanUtils
import com.common.base.utils.ViewUtils
import com.module.ble.data.bean.CusChartData
import com.module.ble.db.table.UserStand
import com.module.ble.repo.UserStandRepo
import com.module.ble.utils.AllCardTypeConfig
import com.module.ble.utils.common24DataConvert
import com.module.ble.utils.groupUserStandByQualityAndType
import com.module.ble.widget.StandingDurationColumnarChart
import com.module.overview.R
import java.util.Calendar

/**
 *
 * 作者：sosou
 *
 * 版本：1.0
 *
 * 创建日期：2025/09/15
 *
 * 描述：活动-站立时长卡片
 *
 * 修订历史：完成度100%
 *
 */
class OvActivityStandingDurationCardProvider(time:Long,
                                             override val itemViewType: Int = AllCardTypeConfig.TYPE_CARD_ACTIVITY_STANDING_DURATION,
                                             override val layoutId: Int = R.layout.overview_activity_standing_duration_crad_provider
) : BaseItemProvider<HistoryDetailsModel>() {

    private var curTime = time

    private var columnarChart: StandingDurationColumnarChart? = null
    private var tvStandingDuration: TextView? = null
    private var tvTotalStanding: TextView? = null

    // 每天24个时间区间数据 - 使用List<Pair>格式
    private val theDays24Pairs = mutableListOf<Pair<String, MutableList<UserStand>>>()

    private val hoursHint by lazy { ViewUtils.getString(R.string.common_hours_hint) }
    private val minutesHint by lazy { ViewUtils.getString(R.string.common_minutes_hint) }

    init {
    }

    override fun convert(helper: BaseViewHolder, item: HistoryDetailsModel) {
        // 设置Y轴阶段
        columnarChart?.setYAxisStages(
            floatArrayOf(0f, 50f, 100f), // 阶段分界点
        )

        getTheDayActivityData()
    }


    override fun onViewHolderCreated(viewHolder: BaseViewHolder, viewType: Int) {
        tvStandingDuration = viewHolder.getView(R.id.tvStandingDuration)
        tvTotalStanding = viewHolder.getView(R.id.tvTotalStanding)
        columnarChart = viewHolder.getView(R.id.candlestickChart)
        columnarChart?.setTouchEnabled(false)
        columnarChart?.setBarRounding(enableTop = false, enableBottom = false)

        super.onViewHolderCreated(viewHolder, viewType)
    }

    /**
     * 获取当天站立信息
     */
    fun getTheDayActivityData(){
        if (curTime <=0) return

        doOnIOThread {
            UserStandRepo.instance.findByOneDay(curTime)?.let { originalListIt->
                //测试数据
//////                val originalListIt :List<UserStand> = JsonUtils.fromJsonList("[{\"createdTime\":1755792060000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1755792060000,\"standType\":0},{\"createdTime\":1755792840000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1755792840000,\"standType\":0},{\"createdTime\":1755792900000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1755792900000,\"standType\":1},{\"createdTime\":1755792960000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1755792960000,\"standType\":1},{\"createdTime\":1755796620000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1755796620000,\"standType\":1},{\"createdTime\":1755796680000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1755796680000,\"standType\":0},{\"createdTime\":1755797880000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1755797880000,\"standType\":1},{\"createdTime\":1755798180000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1755798180000,\"standType\":1},{\"createdTime\":1755798060000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1755798060000,\"standType\":1},{\"createdTime\":1755798480000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1755798480000,\"standType\":0},{\"createdTime\":1755798600000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1755798600000,\"standType\":1},{\"createdTime\":1755799200000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1755799200000,\"standType\":1}]")
//                val originalListIt :List<UserStand> = JsonUtils.fromJsonList("[{\"createdTime\":1755792060000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1755792060000,\"standType\":0},{\"createdTime\":1755792840000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1755792840000,\"standType\":0},{\"createdTime\":1755792900000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1755792900000,\"standType\":1},{\"createdTime\":1755792960000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1755792960000,\"standType\":1},\n" +
//                        "{\"createdTime\":1755793500000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1755793500000,\"standType\":1},{\"createdTime\":1755796620000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1755796620000,\"standType\":1},{\"createdTime\":1755796680000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1755796680000,\"standType\":0},{\"createdTime\":1755797880000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1755797880000,\"standType\":1},{\"createdTime\":1755798180000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1755798180000,\"standType\":1},{\"createdTime\":1755798060000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1755798060000,\"standType\":1},{\"createdTime\":1755798480000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1755798480000,\"standType\":0},{\"createdTime\":1755798600000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1755798600000,\"standType\":1},{\"createdTime\":1755799200000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1755799200000,\"standType\":1}]")

                if (originalListIt.isNullOrEmpty()) return@doOnIOThread

//                val listItStr = JsonUtils.toJson(originalListIt)

//                val groupedData = common48DataConvertByStepsRelatedRecord(mType=1,doSum = true,curTime=curTime, originalList=originalListIt)
//                val groupedData = common24DataConvert(doSum = true,curTime=curTime, originalList=originalListIt)
//                val groupedDataStr = JsonUtils.toJson(groupedData)

                //将originalListIt按照一天24个区间块分组（每一小时为一个区间）
                theDays24Pairs.clear()
                // 获取curTime当天的0点时间戳
                val calendar = Calendar.getInstance()
                calendar.timeInMillis = curTime
//                calendar.timeInMillis = 1755792060000
                calendar.set(Calendar.HOUR_OF_DAY, 0)
                calendar.set(Calendar.MINUTE, 0)
                calendar.set(Calendar.SECOND, 0)
                calendar.set(Calendar.MILLISECOND, 0)
                val startOfDay = calendar.timeInMillis

                // 创建24个时间区间
                for (index in 0 until 24) {
                    val intervalStartTime = startOfDay + (index * 60 * 60 * 1000L) // 每小时的时间偏移
                    val intervalEndTime = startOfDay + ((index + 1) * 60 * 60 * 1000L) // 下一小时的开始时间

                    // 生成时间区间字符串（如：00:00~01:00）
                    val startHour = String.format("%02d:00", index)
                    val endHour = String.format("%02d:00", (index + 1) % 24)
                    val timeRangeString = "$startHour~$endHour"

                    // 筛选该时间区间内的UserStand数据
                    val intervalData = originalListIt.filter { userStand ->
                        userStand.createdTime in intervalStartTime until intervalEndTime
                    }.toMutableList()

                    // 添加到theDays24Pairs
                    theDays24Pairs.add(Pair(timeRangeString, intervalData))
                }

//                val theDays24PairsStr = JsonUtils.toJson(theDays24Pairs)

                // 处理相邻区间之间的时间间隔，插入补充数据
                for (i in 0 until theDays24Pairs.size - 1) {
                    val currentInterval = theDays24Pairs[i]
                    val nextInterval = theDays24Pairs[i + 1]

                    // 获取当前区间的最后一条数据
                    val currentLastData = currentInterval.second.lastOrNull()
                    // 获取下一个区间的第一条数据
                    val nextFirstData = nextInterval.second.firstOrNull()

                    // 只处理当前区间和下一个区间都有数据的情况
                    if (currentLastData != null && nextFirstData != null) {
                        // 计算时间间隔（毫秒）
                        val timeDifference = nextFirstData.createdTime - currentLastData.createdTime
                        val thirtyMinutesInMillis = 30 * 60 * 1000L // 30分钟的毫秒数

                        // 如果时间间隔大于等于30分钟，插入补充数据
                        if (timeDifference >= thirtyMinutesInMillis) {
                            // 计算当前区间的截止时间
                            val intervalEndTime = startOfDay + ((i + 1) * 60 * 60 * 1000L)

                            // 创建补充数据，使用最后一条数据的standType
                            val supplementData = UserStand().apply {
                                createdTime = intervalEndTime
                                dataVersion = currentLastData.dataVersion
                                endTime = currentLastData.endTime
                                firmName = currentLastData.firmName
                                inDateTime = intervalEndTime
                                macAddress = currentLastData.macAddress
                                standType = currentLastData.standType // 使用最后一条数据的standType
                                sysStat = currentLastData.sysStat
                                timeZone = currentLastData.timeZone
                            }

                            // 在当前区间的second末尾添加补充数据
                            currentInterval.second.add(supplementData)
                        }
                    }
                }

//                val theDays24PairsStr2 = JsonUtils.toJson(theDays24Pairs)


                val theDays24DurationPairs = mutableListOf<Pair<String, List<CusChartData>>>()

                // 创建24个时间区间块的CusChartData数组
                val result = mutableListOf<CusChartData>()

                for (index in 0 until 24) {
                    val timeOffset = index * 60 * 60 * 1000L // 每60分钟（1小时）的时间偏移
                    val intervalStartTime = startOfDay + timeOffset
                    val intervalEndTime = startOfDay + timeOffset + (60 * 60 * 1000L) // 加60分钟作为结束时间

                    // 生成时间区间字符串（如：00:00~01:00）
                    val startHour = String.format("%02d:00", index)
                    val endHour = String.format("%02d:00", (index + 1) % 24)
                    val timeRangeString = "$startHour~$endHour"

                    result.add(
                        CusChartData(
                            createdTime = intervalStartTime,
                            endTime = intervalEndTime,
                            mValue = 0f,
                            minValue = 0f,
                            dayNum = 0
                        )
                    )

                    theDays24DurationPairs.add(Pair(timeRangeString, groupUserStandByQualityAndType(theDays24Pairs[index].second)))
                }

//                val resultStr = JsonUtils.toJson(result)
//                val theDays24DurationPairsStr = JsonUtils.toJson(theDays24DurationPairs)

                theDays24DurationPairs.forEachIndexed { index, data ->
                    result[index].timeLong = data.second.sumOf { it.timeLong }
                    result[index].mValue = if (result[index].timeLong>0) 1f else 0f
                }

//                val resultStr2 = JsonUtils.toJson(result)

                val standingDuration = result.count { it.mValue >= 1 }
//                val totalStanding = result.sumOf { it.timeLong }
                val totalStanding = originalListIt.count { it.standType == 1L } * 5//改成根据条数

                doOnUiThread {
                    tvStandingDuration?.let {tvIt->

                        SpanUtils.create()
                            .addForeColorSection(standingDuration.toString(),
                                ViewUtils.getColor(R.color.text_content)
                            )
                            .setAbsSize(standingDuration.toString(), 20)
                            .setStyle(standingDuration.toString(), Typeface.BOLD)
                            .addSection(hoursHint)
                            .showIn(tvIt)
                    }

                    tvTotalStanding?.let {tvIt->
                        SpanUtils.create()
                            .addForeColorSection(totalStanding.toString(),
                                ViewUtils.getColor(R.color.text_content)
                            )
                            .setAbsSize(totalStanding.toString(), 20)
                            .setStyle(totalStanding.toString(), Typeface.BOLD)
                            .addSection(minutesHint)
                            .showIn(tvIt)
                    }
                    columnarChart?.setData(result)
                }
            }
        }
    }
}